<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="将特定类别出现的概率与该类别出现时每一个特征值出现的概率取乘积，以此表示该组特征值被归属为该类别的概率。以此计算该组特征值被归属为每一个类别的概率，择其最大的概率所对应的类别作为预测结果。">
<meta name="keywords" content="AI进阶,机器学习">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习-分类问题">
<meta property="og:url" content="https://rencheng.cc/2019/02/22/ml/分类/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="将特定类别出现的概率与该类别出现时每一个特征值出现的概率取乘积，以此表示该组特征值被归属为该类别的概率。以此计算该组特征值被归属为每一个类别的概率，择其最大的概率所对应的类别作为预测结果。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-02-22T07:13:28.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习-分类问题">
<meta name="twitter:description" content="将特定类别出现的概率与该类别出现时每一个特征值出现的概率取乘积，以此表示该组特征值被归属为该类别的概率。以此计算该组特征值被归属为每一个类别的概率，择其最大的概率所对应的类别作为预测结果。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2019/02/22/ml/分类/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>机器学习-分类问题 | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2019/02/22/ml/分类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">机器学习-分类问题

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-02-22 15:13:28" itemprop="dateCreated datePublished" datetime="2019-02-22T15:13:28+08:00">2019-02-22</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">27k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>将特定类别出现的概率与该类别出现时每一个特征值出现的概率取乘积，以此表示该组特征值被归属为该类别的概率。以此计算该组特征值被归属为每一个类别的概率，择其最大的概率所对应的类别作为预测结果。<br><a id="more"></a></p>
<h1 id="简单分类"><a href="#简单分类" class="headerlink" title="简单分类"></a>简单分类</h1><figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">x1 x2  -&gt;  y</span><br><span class="line"><span class="number">3</span>   <span class="number">1</span>      <span class="number">0</span></span><br><span class="line"><span class="number">2</span>   <span class="number">5</span>      <span class="number">1</span></span><br><span class="line"><span class="number">1</span>   <span class="number">8</span>      <span class="number">1</span></span><br><span class="line"><span class="number">6</span>   <span class="number">4</span>      <span class="number">0</span></span><br><span class="line"><span class="number">5</span>   <span class="number">2</span>      <span class="number">0</span></span><br><span class="line"><span class="number">3</span>   <span class="number">5</span>      <span class="number">1</span></span><br><span class="line"><span class="number">4</span>   <span class="number">7</span>      <span class="number">1</span></span><br><span class="line"><span class="number">4</span>   <span class="number">1</span>      <span class="number">0</span>   </span><br><span class="line"><span class="number">3</span>   <span class="number">9</span>      ? -&gt; <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p>$x_1 &gt; x_2: y = 0$<br>$x_1 &lt; x_2: y = 1$</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = np.array([</span><br><span class="line">	[<span class="number">3</span>, <span class="number">1</span>],</span><br><span class="line">	[<span class="number">2</span>, <span class="number">5</span>],</span><br><span class="line">	[<span class="number">1</span>, <span class="number">8</span>],</span><br><span class="line">	[<span class="number">6</span>, <span class="number">4</span>],</span><br><span class="line">	[<span class="number">5</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">3</span>, <span class="number">5</span>],</span><br><span class="line">	[<span class="number">4</span>, <span class="number">7</span>],</span><br><span class="line">	[<span class="number">4</span>,<span class="number">-1</span>]])</span><br><span class="line">y = np.array([<span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>])</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = np.zeros(len(flat_x), dtype=int)</span><br><span class="line">flat_y[flat_x[:, <span class="number">0</span>] &lt; flat_x[:, <span class="number">1</span>]] = <span class="number">1</span> <span class="comment"># 分类规则</span></span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'Simple Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Simple Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h1 id="逻辑回归分类器"><a href="#逻辑回归分类器" class="headerlink" title="逻辑回归分类器"></a>逻辑回归分类器</h1><p>$y = w0 + w1x$</p>
<p>$z = \frac{1}{1 + e^{-y}}$</p>
<p>x样本被归属为1类别的概率</p>
<p><strong>梯度下降</strong><br>model=LogisticRegression(solver=’liblinear’, C=正则强度)<br>$w0 + w1 \times 1 + w2 \times 2 = 0$<br><figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">``` py</span><br><span class="line"><span class="built_in">import</span> numpy as np</span><br><span class="line"><span class="built_in">import</span> sklearn.linear_model as lm</span><br><span class="line"><span class="built_in">import</span> matplotlib.pyplot as mp</span><br><span class="line"><span class="attr">x</span> = np.array([</span><br><span class="line">	[<span class="number">3</span>, <span class="number">1</span>],</span><br><span class="line">	[<span class="number">2</span>, <span class="number">5</span>],</span><br><span class="line">	[<span class="number">1</span>, <span class="number">8</span>],</span><br><span class="line">	[<span class="number">6</span>, <span class="number">4</span>],</span><br><span class="line">	[<span class="number">5</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">3</span>, <span class="number">5</span>],</span><br><span class="line">	[<span class="number">4</span>, <span class="number">7</span>],</span><br><span class="line">	[<span class="number">4</span>,-<span class="number">1</span>]])</span><br><span class="line"><span class="attr">y</span> = np.array([<span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>])</span><br><span class="line"><span class="comment"># 逻辑回归分类器</span></span><br><span class="line"><span class="attr">model</span> = lm.LogisticRegression(</span><br><span class="line">	<span class="attr">solver='liblinear',</span> <span class="attr">C=1)</span></span><br><span class="line">model.fit(x, y)</span><br><span class="line">l, r, <span class="attr">h</span> = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, <span class="attr">v</span> = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line"><span class="attr">grid_x</span> = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line"><span class="attr">flat_x</span> = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line"><span class="attr">flat_y</span> = model.predict(flat_x)</span><br><span class="line"><span class="attr">grid_y</span> = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure('Logistic Classification',</span><br><span class="line">	<span class="attr">facecolor='lightgray')</span></span><br><span class="line">mp.title('Logistic Classification', <span class="attr">fontsize=20)</span></span><br><span class="line">mp.xlabel('x', <span class="attr">fontsize=14)</span></span><br><span class="line">mp.ylabel('y', <span class="attr">fontsize=14)</span></span><br><span class="line">mp.tick_params(<span class="attr">labelsize=10)</span></span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, <span class="attr">cmap='gray')</span></span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], <span class="attr">c=y,</span> <span class="attr">cmap='brg',</span> <span class="attr">s=80)</span></span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">xxxx A <span class="number">1</span>    <span class="number">0</span>     <span class="number">0</span></span><br><span class="line">xxxx B <span class="number">0</span>    <span class="number">1</span>     <span class="number">0</span></span><br><span class="line">xxxx C <span class="number">0</span>    <span class="number">0</span>     <span class="number">1</span></span><br><span class="line">            A    B     C</span><br><span class="line">........   <span class="number">0.2</span>  <span class="number">0.6</span>  <span class="number">0.4</span>   B</span><br><span class="line">........   <span class="number">0.6</span>  <span class="number">0.1</span>  <span class="number">0.3</span>   A</span><br><span class="line">........   <span class="number">0.4</span>  <span class="number">0.2</span>  <span class="number">0.8</span>   C</span><br></pre></td></tr></table></figure>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.linear_model <span class="keyword">as</span> lm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x = np.array([</span><br><span class="line">	[<span class="number">4</span>, <span class="number">7</span>],</span><br><span class="line">	[<span class="number">3.5</span>, <span class="number">8</span>],</span><br><span class="line">	[<span class="number">3.1</span>, <span class="number">6.2</span>],</span><br><span class="line">	[<span class="number">0.5</span>, <span class="number">1</span>],</span><br><span class="line">	[<span class="number">1</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">1.2</span>, <span class="number">1.9</span>],</span><br><span class="line">	[<span class="number">6</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">5.7</span>,<span class="number">1.5</span>],</span><br><span class="line">	[<span class="number">5.4</span>, <span class="number">2.2</span>]])</span><br><span class="line">y = np.array([<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>])</span><br><span class="line"><span class="comment"># 逻辑回归分类器</span></span><br><span class="line">model = lm.LogisticRegression(</span><br><span class="line">	solver=<span class="string">'liblinear'</span>, C=<span class="number">1000</span>)</span><br><span class="line">model.fit(x, y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'Logistic Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Logistic Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h1 id="朴素贝叶斯分类"><a href="#朴素贝叶斯分类" class="headerlink" title="朴素贝叶斯分类"></a>朴素贝叶斯分类</h1><figure class="highlight excel"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span> <span class="number">2</span> <span class="number">3</span> -&gt; <span class="number">0</span></span><br><span class="line"><span class="number">4</span> <span class="number">5</span> <span class="number">6</span> -&gt; <span class="number">1</span></span><br><span class="line"><span class="number">7</span> <span class="number">8</span> <span class="number">9</span> -&gt; <span class="number">2</span></span><br><span class="line">...</span><br><span class="line"><span class="number">1</span> <span class="number">5</span> <span class="number">9</span> -&gt; ? <span class="number">0</span>  <span class="number">0.7</span></span><br><span class="line">                  <span class="number">1</span>  <span class="number">0.5</span></span><br><span class="line">                  <span class="number">2</span>  <span class="number">0.8</span> *</span><br><span class="line">P(<span class="symbol">x1</span>,<span class="symbol">x2</span>,<span class="symbol">x3</span>,C)</span><br><span class="line">=P(<span class="symbol">x1</span>|<span class="symbol">x2</span>,<span class="symbol">x3</span>,C)P(<span class="symbol">x2</span>,<span class="symbol">x3</span>,C)</span><br><span class="line">=P(<span class="symbol">x1</span>|<span class="symbol">x2</span>,<span class="symbol">x3</span>,C)P(<span class="symbol">x2</span>|<span class="symbol">x3</span>,C)P(<span class="symbol">x3</span>,C)</span><br><span class="line">=P(<span class="symbol">x1</span>|<span class="symbol">x2</span>,<span class="symbol">x3</span>,C)P(<span class="symbol">x2</span>|<span class="symbol">x3</span>,C)P(<span class="symbol">x3</span>|C)P(C)</span><br><span class="line">朴素：条件独立，特征值之间没有约束性。</span><br><span class="line">=P(<span class="symbol">x1</span>|C)P(<span class="symbol">x2</span>|C)P(<span class="symbol">x3</span>|C)P(C)</span><br></pre></td></tr></table></figure>
<p>将特定类别出现的概率与该类别出现时每一个特征值出现的概率取乘积，以此表示该组特征值被归属为该类别的概率。以此计算该组特征值被归属为每一个类别的概率，择其最大的概率所对应的类别作为预测结果。<br>关于某个特征值在特定类别出现时的概率，可以通过事先已知的概率密度函数或概率质量函数计算得到。<br>体现历史数据所表现出的统计规律，同时不存在对分类边界的线性约束，但是对于统计规则不明且样本数量较少的场合不适用。<br>import sklearn.naive_bayes as nb<br>model = nb.GaussianNB()<br>基于高斯分布即正态分布的朴素贝叶斯分类器<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.naive_bayes <span class="keyword">as</span> nb</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple1.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 朴素贝叶斯分类器</span></span><br><span class="line">model = nb.GaussianNB()</span><br><span class="line">model.fit(x, y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">mp.figure(<span class="string">'NB Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'NB Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y, cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(x[:, <span class="number">0</span>], x[:, <span class="number">1</span>], c=y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="1-划分训练集和测试集"><a href="#1-划分训练集和测试集" class="headerlink" title="1. 划分训练集和测试集"></a>1. 划分训练集和测试集</h2><p>import sklearn.model_selection as ms;<br>ms.train_test_split(<br>    输入集, 输出集, test_size=测试集比例,<br>    random_state=随机种子)-&gt;<br>    训练输入集，测试输入集，训练输出集，测试输出集<br>该函数对每一个类别单独洗牌，然后根据test_size参数提取相应比例的样本用于测试，其余样本用于训练，各个类别的分布比例在训练集和测试集中都是一致的。</p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.naive_bayes <span class="keyword">as</span> nb</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple1.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 按3:1的比例划分训练集和测试集</span></span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 朴素贝叶斯分类器</span></span><br><span class="line">model = nb.GaussianNB()</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print((pred_test_y == test_y).sum() /</span><br><span class="line">	pred_test_y.size)</span><br><span class="line">mp.figure(<span class="string">'NB Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'NB Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(test_x[:, <span class="number">0</span>], test_x[:, <span class="number">1</span>],</span><br><span class="line">	c=test_y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="2-评价分类器的性能"><a href="#2-评价分类器的性能" class="headerlink" title="2. 评价分类器的性能"></a>2. 评价分类器的性能</h2><p>查准率：对于某个类别，找对的/找出来的，正确性。<br>召回率：对于某个类别，找对的/该类别样本数，完整性。<br>F1得分：2x查准率x召回率/(查准率+召回率)</p>
<h2 id="3-交叉验证"><a href="#3-交叉验证" class="headerlink" title="3. 交叉验证"></a>3. 交叉验证</h2><p>ms.cross_val_score(模型对象, 输入集, 输出集,<br>    cv=验证次数, scoring=评价指标)-&gt;<br>    每次验证测试集各个类别指标的平均值<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.naive_bayes <span class="keyword">as</span> nb</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple1.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 按3:1的比例划分训练集和测试集</span></span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 朴素贝叶斯分类器</span></span><br><span class="line">model = nb.GaussianNB()</span><br><span class="line"><span class="comment"># 交叉验证</span></span><br><span class="line">pw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'precision_weighted'</span>)</span><br><span class="line">print(pw.mean())</span><br><span class="line">rw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'recall_weighted'</span>)</span><br><span class="line">print(rw.mean())</span><br><span class="line">fw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'f1_weighted'</span>)</span><br><span class="line">print(fw.mean())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print((pred_test_y == test_y).sum() /</span><br><span class="line">	pred_test_y.size)</span><br><span class="line">mp.figure(<span class="string">'NB Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'NB Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(test_x[:, <span class="number">0</span>], test_x[:, <span class="number">1</span>],</span><br><span class="line">	c=test_y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="4-混淆矩阵"><a href="#4-混淆矩阵" class="headerlink" title="4. 混淆矩阵"></a>4. 混淆矩阵</h2><p>import sklearn.metrics as sm<br>sm.confusion_matrix(实际输出, 预测输出)-&gt;混淆矩阵<br>每一行对应一个实际类别<br>每一列对应一个预测类别<br>对角线上元素表示各个类别分类正确的样本数，其它位置的元素表示分类误差。<br>对角线上元素/其所在列元素之和 = 该类别的查准率 \ F1得分<br>对角线上元素/其所在行元素之和 = 该类别的召回率 /<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.naive_bayes <span class="keyword">as</span> nb</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple1.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 按3:1的比例划分训练集和测试集</span></span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 朴素贝叶斯分类器</span></span><br><span class="line">model = nb.GaussianNB()</span><br><span class="line"><span class="comment"># 交叉验证</span></span><br><span class="line">pw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'precision_weighted'</span>)</span><br><span class="line">print(pw.mean())</span><br><span class="line">rw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'recall_weighted'</span>)</span><br><span class="line">print(rw.mean())</span><br><span class="line">fw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'f1_weighted'</span>)</span><br><span class="line">print(fw.mean())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print((pred_test_y == test_y).sum() /</span><br><span class="line">	pred_test_y.size)</span><br><span class="line"><span class="comment"># 混淆矩阵</span></span><br><span class="line">cm = sm.confusion_matrix(test_y, pred_test_y)</span><br><span class="line">print(cm)</span><br><span class="line">mp.figure(<span class="string">'NB Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'NB Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(test_x[:, <span class="number">0</span>], test_x[:, <span class="number">1</span>],</span><br><span class="line">	c=test_y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="5-分类报告"><a href="#5-分类报告" class="headerlink" title="5. 分类报告"></a>5. 分类报告</h2><p>针对每一个类别的评价指标及平均值。<br>sm.classification_report(实际输出, 预测输出)-&gt;分类报告<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.naive_bayes <span class="keyword">as</span> nb</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple1.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line"><span class="comment"># 按3:1的比例划分训练集和测试集</span></span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 朴素贝叶斯分类器</span></span><br><span class="line">model = nb.GaussianNB()</span><br><span class="line"><span class="comment"># 交叉验证</span></span><br><span class="line">pw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'precision_weighted'</span>)</span><br><span class="line">print(pw.mean())</span><br><span class="line">rw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'recall_weighted'</span>)</span><br><span class="line">print(rw.mean())</span><br><span class="line">fw = ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'f1_weighted'</span>)</span><br><span class="line">print(fw.mean())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print((pred_test_y == test_y).sum() /</span><br><span class="line">	pred_test_y.size)</span><br><span class="line"><span class="comment"># 混淆矩阵</span></span><br><span class="line">cm = sm.confusion_matrix(test_y, pred_test_y)</span><br><span class="line">print(cm)</span><br><span class="line"><span class="comment"># 分类报告</span></span><br><span class="line">cr = sm.classification_report(test_y, pred_test_y)</span><br><span class="line">print(cr)</span><br><span class="line">mp.figure(<span class="string">'NB Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'NB Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">mp.scatter(test_x[:, <span class="number">0</span>], test_x[:, <span class="number">1</span>],</span><br><span class="line">	c=test_y, cmap=<span class="string">'brg'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h1 id="十一、决策树分类"><a href="#十一、决策树分类" class="headerlink" title="十一、决策树分类"></a>十一、决策树分类</h1><p>投票<br>基于随机森林分类器的汽车品质评估<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.preprocessing <span class="keyword">as</span> sp</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line">data = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/car.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data.append(line[:<span class="number">-1</span>].split(<span class="string">','</span>))</span><br><span class="line">data = np.array(data).T</span><br><span class="line">encoders, train_x = [], []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	encoder = sp.LabelEncoder()</span><br><span class="line">	<span class="keyword">if</span> row &lt; len(data) - <span class="number">1</span>:</span><br><span class="line">		train_x.append(</span><br><span class="line">			encoder.fit_transform(data[row]))</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		train_y = encoder.fit_transform(data[row])</span><br><span class="line">	encoders.append(encoder)</span><br><span class="line">train_x = np.array(train_x).T</span><br><span class="line"><span class="comment"># 随机森林分类器</span></span><br><span class="line">model = se.RandomForestClassifier(</span><br><span class="line">	max_depth=<span class="number">8</span>, n_estimators=<span class="number">200</span>,</span><br><span class="line">	random_state=<span class="number">7</span>)</span><br><span class="line">print(ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">3</span>, scoring=<span class="string">'f1_weighted'</span>).mean())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">data = [</span><br><span class="line">	[<span class="string">'high'</span>, <span class="string">'med'</span>, <span class="string">'5more'</span>, <span class="string">'4'</span>, <span class="string">'big'</span>, <span class="string">'low'</span>],</span><br><span class="line">	[<span class="string">'high'</span>, <span class="string">'high'</span>, <span class="string">'4'</span>, <span class="string">'4'</span>, <span class="string">'med'</span>, <span class="string">'med'</span>],</span><br><span class="line">	[<span class="string">'low'</span>, <span class="string">'low'</span>, <span class="string">'2'</span>, <span class="string">'4'</span>, <span class="string">'small'</span>, <span class="string">'high'</span>],</span><br><span class="line">	[<span class="string">'low'</span>, <span class="string">'med'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>, <span class="string">'med'</span>, <span class="string">'high'</span>]]</span><br><span class="line">data = np.array(data).T</span><br><span class="line">test_x = []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	encoder = encoders[row]</span><br><span class="line">	test_x.append(encoder.transform(data[row]))</span><br><span class="line">test_x = np.array(test_x).T</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(encoders[<span class="number">-1</span>].inverse_transform(pred_test_y))</span><br></pre></td></tr></table></figure></p>
<h2 id="1-验证曲线"><a href="#1-验证曲线" class="headerlink" title="1. 验证曲线"></a>1. 验证曲线</h2><p>模型的交叉验证得分=f(模型超参数)<br>ms.validation_curve(<br>    模型对象, 输入集, 输出集, 超参数名, 超参数表, cv=验证次数)<br>    -&gt;训练集得分矩阵, 测试集得分矩阵<br>                     验证1 验证2 …<br>超参数取值1                          -&gt; 平均<br>超参数取值2<br>…<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.preprocessing <span class="keyword">as</span> sp</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">data = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/car.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data.append(line[:<span class="number">-1</span>].split(<span class="string">','</span>))</span><br><span class="line">data = np.array(data).T</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	encoder = sp.LabelEncoder()</span><br><span class="line">	<span class="keyword">if</span> row &lt; len(data) - <span class="number">1</span>:</span><br><span class="line">		x.append(</span><br><span class="line">			encoder.fit_transform(data[row]))</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		y = encoder.fit_transform(data[row])</span><br><span class="line">x = np.array(x).T</span><br><span class="line"><span class="comment"># 随机森林分类器</span></span><br><span class="line">model = se.RandomForestClassifier(</span><br><span class="line">	max_depth=<span class="number">8</span>, random_state=<span class="number">7</span>)</span><br><span class="line">n_estimators = np.arange(<span class="number">50</span>, <span class="number">550</span>, <span class="number">50</span>)</span><br><span class="line">train_scores1, test_scores1 = \</span><br><span class="line">	ms.validation_curve(model, x, y,</span><br><span class="line">	<span class="string">'n_estimators'</span>, n_estimators, cv=<span class="number">5</span>)</span><br><span class="line">train_means1 = train_scores1.mean(axis=<span class="number">1</span>)</span><br><span class="line">model = se.RandomForestClassifier(</span><br><span class="line">	n_estimators=<span class="number">150</span>, random_state=<span class="number">7</span>)</span><br><span class="line">max_depth = np.arange(<span class="number">1</span>, <span class="number">11</span>)</span><br><span class="line">train_scores2, test_scores2 = \</span><br><span class="line">	ms.validation_curve(model, x, y,</span><br><span class="line">	<span class="string">'max_depth'</span>, max_depth, cv=<span class="number">5</span>)</span><br><span class="line">train_means2 = train_scores2.mean(axis=<span class="number">1</span>)</span><br><span class="line">mp.figure(<span class="string">'n_estimators'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'n_estimators'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'n_estimators'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'F1 Score'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.plot(n_estimators, train_means1, <span class="string">'o-'</span>,</span><br><span class="line">	c=<span class="string">'dodgerblue'</span>, label=<span class="string">'Training'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.figure(<span class="string">'max_depth'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'max_depth'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'max_depth'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'F1 Score'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.plot(max_depth, train_means2, <span class="string">'o-'</span>,</span><br><span class="line">	c=<span class="string">'limegreen'</span>, label=<span class="string">'Training'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="2-学习曲线"><a href="#2-学习曲线" class="headerlink" title="2. 学习曲线"></a>2. 学习曲线</h2><p>模型的交叉验证得分=f(训练集大小)<br>ms.learning_curve(<br>    模型对象, 输入集, 输出集, 训练集大小列表, cv=验证次数)<br>    -&gt;训练集大小列表, 训练集得分矩阵, 测试集得分矩阵<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.preprocessing <span class="keyword">as</span> sp</span><br><span class="line"><span class="keyword">import</span> sklearn.ensemble <span class="keyword">as</span> se</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">data = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/car.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data.append(line[:<span class="number">-1</span>].split(<span class="string">','</span>))</span><br><span class="line">data = np.array(data).T</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	encoder = sp.LabelEncoder()</span><br><span class="line">	<span class="keyword">if</span> row &lt; len(data) - <span class="number">1</span>:</span><br><span class="line">		x.append(</span><br><span class="line">			encoder.fit_transform(data[row]))</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		y = encoder.fit_transform(data[row])</span><br><span class="line">x = np.array(x).T</span><br><span class="line"><span class="comment"># 随机森林分类器</span></span><br><span class="line">model = se.RandomForestClassifier(</span><br><span class="line">	max_depth=<span class="number">8</span>, n_estimators=<span class="number">150</span>,</span><br><span class="line">	random_state=<span class="number">7</span>)</span><br><span class="line">train_sizes = np.linspace(<span class="number">0.1</span>, <span class="number">1</span>, <span class="number">10</span>)</span><br><span class="line">print(train_sizes)</span><br><span class="line">train_sizes, train_scores, test_scores = \</span><br><span class="line">	ms.learning_curve(model, x, y,</span><br><span class="line">	train_sizes=train_sizes, cv=<span class="number">5</span>)</span><br><span class="line">train_means = train_scores.mean(axis=<span class="number">1</span>)</span><br><span class="line">test_means = test_scores.mean(axis=<span class="number">1</span>)</span><br><span class="line">mp.figure(<span class="string">'Leaning Curve'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Leaning Curve'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'train_size'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'F1 Score'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">mp.plot(train_sizes, train_means, <span class="string">'o-'</span>,</span><br><span class="line">	c=<span class="string">'dodgerblue'</span>, label=<span class="string">'Training'</span>)</span><br><span class="line">mp.plot(train_sizes, test_means, <span class="string">'o-'</span>,</span><br><span class="line">	c=<span class="string">'orangered'</span>, label=<span class="string">'Testing'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.tight_layout()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h1 id="十二、支持向量机"><a href="#十二、支持向量机" class="headerlink" title="十二、支持向量机"></a>十二、支持向量机</h1><h2 id="1-原理"><a href="#1-原理" class="headerlink" title="1. 原理"></a>1. 原理</h2><p>寻求最优的分类边界，即被支持向量所夹持的分类带宽度达到最大值，取其中心线作为分类边界。</p>
<pre><code>* 安全性：分类带最宽
* 公平性：分类带中心线
* 简单性：线性边界，分割超平面
* 对于在原始维度空间中无法线性分割的样本，通过特定的核函数增加特征，即升高维度，在高维度空间寻求分割超平面。
</code></pre><h2 id="2-接口"><a href="#2-接口" class="headerlink" title="2. 接口"></a>2. 接口</h2><p>import sklearn.svm as svm<br>分类器模型=svm.SVC(kernel=核函数类型, …)<br>回归器模型=svm.SVR(kernel=核函数类型, …)</p>
<h2 id="3-线性核函数"><a href="#3-线性核函数" class="headerlink" title="3. 线性核函数"></a>3. 线性核函数</h2><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple2.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 支持向量机分类器</span></span><br><span class="line">model = svm.SVC(kernel=<span class="string">'linear'</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>],</span><br><span class="line">	c=<span class="string">'orangered'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>],</span><br><span class="line">	c=<span class="string">'limegreen'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="4-多项式核函数"><a href="#4-多项式核函数" class="headerlink" title="4. 多项式核函数"></a>4. 多项式核函数</h2><p>x1 x2<br>x1 x2 x1^2 x2^2 x1x2 x1^2x2 x1x2^2 x1^3 x2^3<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple2.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 支持向量机分类器</span></span><br><span class="line">model = svm.SVC(kernel=<span class="string">'poly'</span>, degree=<span class="number">3</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>], c=<span class="string">'orangered'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>], c=<span class="string">'limegreen'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="5-径向基核函数"><a href="#5-径向基核函数" class="headerlink" title="5. 径向基核函数"></a>5. 径向基核函数</h2><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple2.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 支持向量机分类器</span></span><br><span class="line">model = svm.SVC(kernel=<span class="string">'rbf'</span>, gamma=<span class="number">0.01</span>, C=<span class="number">600</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>], c=<span class="string">'orangered'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>], c=<span class="string">'limegreen'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h2 id="6-样本均衡"><a href="#6-样本均衡" class="headerlink" title="6. 样本均衡"></a>6. 样本均衡</h2><p>svm.SVC(…, class_weight=’balanced’)<br>通过为不同类别的样本设置不同的权重，平衡比例相差较大的类别为分类器所带来的不同影响。<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/imbalance.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 支持向量机分类器</span></span><br><span class="line">model = svm.SVC(kernel=<span class="string">'linear'</span>,</span><br><span class="line">	class_weight=<span class="string">'balanced'</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>],</span><br><span class="line">	c=<span class="string">'orangered'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>],</span><br><span class="line">	c=<span class="string">'limegreen'</span>, s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="7-置信概率"><a href="#7-置信概率" class="headerlink" title="7. 置信概率"></a>7. 置信概率</h2><p>根据样本与分类边界的距离表示该样本被分类器归属每个类别的概率。<br>model = svm.SVC(…, probablity=True, …)<br>model.predict_proba(输入集)-&gt;概率矩阵<br>概率矩阵中的一行对应输入集中的要给样本，一列表示一个的类别，而其中的值表示该样本被归属为特定类别的概率。<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple2.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 支持向量机分类器</span></span><br><span class="line">model = svm.SVC(kernel=<span class="string">'rbf'</span>, gamma=<span class="number">0.01</span>, C=<span class="number">600</span>,</span><br><span class="line">	probability=<span class="literal">True</span>)</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">prob_x = np.array([</span><br><span class="line">	[<span class="number">2</span>, <span class="number">1.5</span>],</span><br><span class="line">	[<span class="number">8</span>, <span class="number">9</span>],</span><br><span class="line">	[<span class="number">4.8</span>, <span class="number">5.2</span>],</span><br><span class="line">	[<span class="number">4</span>, <span class="number">4</span>],</span><br><span class="line">	[<span class="number">2.5</span>, <span class="number">7</span>],</span><br><span class="line">	[<span class="number">7.6</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">5.4</span>, <span class="number">5.9</span>]])</span><br><span class="line">print(prob_x)</span><br><span class="line">pred_prob_y = model.predict(prob_x)</span><br><span class="line">print(pred_prob_y)</span><br><span class="line">probs = model.predict_proba(prob_x)</span><br><span class="line">print(probs)</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>], c=<span class="string">'orangered'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>], c=<span class="string">'limegreen'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<h2 id="8-网格搜索"><a href="#8-网格搜索" class="headerlink" title="8. 网格搜索"></a>8. 网格搜索</h2><p>超参数组合列表:<br>[{超参数名: [取值列表], 超参数名: [取值列表]}, {…}, …]<br>model = ms.GridSearchCV(<br>    基本模型, 超参数组合列表, cv=交叉验证数)<br>model.fit(输入集, 输出集)<br>model -&gt; 用最优超参数组合设置的模型<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="keyword">import</span> sklearn.metrics <span class="keyword">as</span> sm</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line">x, y = [], []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'../data/multiple2.txt'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data = [float(substr) <span class="keyword">for</span> substr</span><br><span class="line">			<span class="keyword">in</span> line.split(<span class="string">','</span>)]</span><br><span class="line">		x.append(data[:<span class="number">-1</span>])</span><br><span class="line">		y.append(data[<span class="number">-1</span>])</span><br><span class="line">x = np.array(x)</span><br><span class="line">y = np.array(y)</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">		random_state=<span class="number">7</span>)</span><br><span class="line"><span class="comment"># 超参数组合列表</span></span><br><span class="line">params = [</span><br><span class="line">    &#123;<span class="string">'kernel'</span>: [<span class="string">'linear'</span>], <span class="string">'C'</span>: [<span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>, <span class="number">1000</span>]&#125;,</span><br><span class="line">    &#123;<span class="string">'kernel'</span>: [<span class="string">'poly'</span>], <span class="string">'C'</span>: [<span class="number">1</span>], <span class="string">'degree'</span>: [<span class="number">2</span>, <span class="number">3</span>]&#125;,</span><br><span class="line">    &#123;<span class="string">'kernel'</span>: [<span class="string">'rbf'</span>], <span class="string">'C'</span>: [<span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>, <span class="number">1000</span>],</span><br><span class="line">     <span class="string">'gamma'</span>: [<span class="number">1</span>, <span class="number">0.1</span>, <span class="number">0.01</span>, <span class="number">0.001</span>]&#125;]</span><br><span class="line">model = ms.GridSearchCV(</span><br><span class="line">	svm.SVC(probability=<span class="literal">True</span>), params, cv=<span class="number">5</span>);</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line"><span class="keyword">for</span> param, score <span class="keyword">in</span> zip(</span><br><span class="line">	model.cv_results_[<span class="string">'params'</span>],</span><br><span class="line">	model.cv_results_[<span class="string">'mean_test_score'</span>]):</span><br><span class="line">	print(param, score)</span><br><span class="line">print(<span class="string">'-'</span> * <span class="number">20</span>)</span><br><span class="line">print(model.best_params_)</span><br><span class="line">l, r, h = x[:, <span class="number">0</span>].min() - <span class="number">1</span>, x[:, <span class="number">0</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">b, t, v = x[:, <span class="number">1</span>].min() - <span class="number">1</span>, x[:, <span class="number">1</span>].max() + <span class="number">1</span>, <span class="number">0.005</span></span><br><span class="line">grid_x = np.meshgrid(np.arange(l, r, h),</span><br><span class="line">	np.arange(b, t, v))</span><br><span class="line">flat_x = np.c_[grid_x[<span class="number">0</span>].ravel(), grid_x[<span class="number">1</span>].ravel()]</span><br><span class="line">flat_y = model.predict(flat_x)</span><br><span class="line">grid_y = flat_y.reshape(grid_x[<span class="number">0</span>].shape)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print(sm.classification_report(test_y, pred_test_y))</span><br><span class="line">prob_x = np.array([</span><br><span class="line">	[<span class="number">2</span>, <span class="number">1.5</span>],</span><br><span class="line">	[<span class="number">8</span>, <span class="number">9</span>],</span><br><span class="line">	[<span class="number">4.8</span>, <span class="number">5.2</span>],</span><br><span class="line">	[<span class="number">4</span>, <span class="number">4</span>],</span><br><span class="line">	[<span class="number">2.5</span>, <span class="number">7</span>],</span><br><span class="line">	[<span class="number">7.6</span>, <span class="number">2</span>],</span><br><span class="line">	[<span class="number">5.4</span>, <span class="number">5.9</span>]])</span><br><span class="line">print(prob_x)</span><br><span class="line">pred_prob_y = model.predict(prob_x)</span><br><span class="line">print(pred_prob_y)</span><br><span class="line">probs = model.predict_proba(prob_x)</span><br><span class="line">print(probs)</span><br><span class="line">mp.figure(<span class="string">'SVM Classification'</span>,</span><br><span class="line">	facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'SVM Classification'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'x'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'y'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.pcolormesh(grid_x[<span class="number">0</span>], grid_x[<span class="number">1</span>], grid_y,</span><br><span class="line">	cmap=<span class="string">'gray'</span>)</span><br><span class="line">C0, C1 = y == <span class="number">0</span>, y == <span class="number">1</span></span><br><span class="line">mp.scatter(x[C0][:, <span class="number">0</span>], x[C0][:, <span class="number">1</span>], c=<span class="string">'orangered'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">mp.scatter(x[C1][:, <span class="number">0</span>], x[C1][:, <span class="number">1</span>], c=<span class="string">'limegreen'</span>,</span><br><span class="line">	s=<span class="number">80</span>)</span><br><span class="line">C0, C1 = pred_prob_y == <span class="number">0</span>, pred_prob_y == <span class="number">1</span>;</span><br><span class="line">mp.scatter(prob_x[C0][:, <span class="number">0</span>], prob_x[C0][:, <span class="number">1</span>],</span><br><span class="line">	marker=<span class="string">'D'</span>, c=<span class="string">'dodgerblue'</span>, s=<span class="number">70</span>)</span><br><span class="line">mp.scatter(prob_x[C1][:, <span class="number">0</span>], prob_x[C1][:, <span class="number">1</span>],</span><br><span class="line">	marker=<span class="string">'D'</span>, c=<span class="string">'deeppink'</span>, s=<span class="number">70</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(len(probs[C0])):</span><br><span class="line">	mp.annotate(<span class="string">'&#123;&#125;% &#123;&#125;%'</span>.format(</span><br><span class="line">		round(probs[C0][:, <span class="number">0</span>][i] * <span class="number">100</span>, <span class="number">2</span>),</span><br><span class="line">		round(probs[C0][:, <span class="number">1</span>][i] * <span class="number">100</span>, <span class="number">2</span>)),</span><br><span class="line">		xy=(prob_x[C0][:, <span class="number">0</span>][i],</span><br><span class="line">			prob_x[C0][:, <span class="number">1</span>][i]),</span><br><span class="line">		xytext=(<span class="number">12</span>, <span class="number">-12</span>),</span><br><span class="line">		textcoords=<span class="string">'offset points'</span>,</span><br><span class="line">		horizontalalignment=<span class="string">'left'</span>,</span><br><span class="line">		verticalalignment=<span class="string">'top'</span>,</span><br><span class="line">		fontsize=<span class="number">9</span>,</span><br><span class="line">		bbox=&#123;<span class="string">'boxstyle'</span>: <span class="string">'round,pad=0.6'</span>,</span><br><span class="line">			<span class="string">'fc'</span>: <span class="string">'deepskyblue'</span>,</span><br><span class="line">			<span class="string">'alpha'</span>: <span class="number">0.8</span>&#125;)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(len(probs[C1])):</span><br><span class="line">	mp.annotate(<span class="string">'&#123;&#125;% &#123;&#125;%'</span>.format(</span><br><span class="line">		round(probs[C1][:, <span class="number">0</span>][i] * <span class="number">100</span>, <span class="number">2</span>),</span><br><span class="line">		round(probs[C1][:, <span class="number">1</span>][i] * <span class="number">100</span>, <span class="number">2</span>)),</span><br><span class="line">		xy=(prob_x[C1][:, <span class="number">0</span>][i],</span><br><span class="line">			prob_x[C1][:, <span class="number">1</span>][i]),</span><br><span class="line">		xytext=(<span class="number">12</span>, <span class="number">-12</span>),</span><br><span class="line">		textcoords=<span class="string">'offset points'</span>,</span><br><span class="line">		horizontalalignment=<span class="string">'left'</span>,</span><br><span class="line">		verticalalignment=<span class="string">'top'</span>,</span><br><span class="line">		fontsize=<span class="number">9</span>,</span><br><span class="line">		bbox=&#123;<span class="string">'boxstyle'</span>: <span class="string">'round,pad=0.6'</span>,</span><br><span class="line">			<span class="string">'fc'</span>: <span class="string">'violet'</span>,</span><br><span class="line">			<span class="string">'alpha'</span>: <span class="number">0.8</span>&#125;)</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure></p>
<p>事件预测<br><figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> sklearn.preprocessing <span class="keyword">as</span> sp</span><br><span class="line"><span class="keyword">import</span> sklearn.model_selection <span class="keyword">as</span> ms</span><br><span class="line"><span class="keyword">import</span> sklearn.svm <span class="keyword">as</span> svm</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DigitEncoder</span><span class="params">()</span>:</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">fit_transform</span><span class="params">(self, x)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> x.astype(int)</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">transform</span><span class="params">(self, x)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> x.astype(int)</span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">inverse_transform</span><span class="params">(self, x)</span>:</span></span><br><span class="line">		<span class="keyword">return</span> x.astype(str)</span><br><span class="line">data = []</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">"../data/event.txt"</span>, <span class="string">'r'</span>) <span class="keyword">as</span> f:</span><br><span class="line">	<span class="keyword">for</span> line <span class="keyword">in</span> f.readlines():</span><br><span class="line">		data.append(line[:<span class="number">-1</span>].split(<span class="string">','</span>))</span><br><span class="line">data = np.delete(np.array(data).T, <span class="number">1</span>, <span class="number">0</span>)</span><br><span class="line">encoders, x = [], []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	<span class="keyword">if</span> data[row, <span class="number">0</span>].isdigit():</span><br><span class="line">		encoder = DigitEncoder()</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		encoder = sp.LabelEncoder()</span><br><span class="line">	<span class="keyword">if</span> row &lt; len(data) - <span class="number">1</span>:</span><br><span class="line">		x.append(encoder.fit_transform(</span><br><span class="line">			data[row]))</span><br><span class="line">	<span class="keyword">else</span>:</span><br><span class="line">		y = encoder.fit_transform(data[row])</span><br><span class="line">	encoders.append(encoder)</span><br><span class="line">x = np.array(x).T</span><br><span class="line">train_x, test_x, train_y, test_y = \</span><br><span class="line">	ms.train_test_split(x, y, test_size=<span class="number">0.25</span>,</span><br><span class="line">	random_state=<span class="number">5</span>)</span><br><span class="line">model = svm.SVC(kernel=<span class="string">'rbf'</span>,</span><br><span class="line">	class_weight=<span class="string">'balanced'</span>)</span><br><span class="line">print(ms.cross_val_score(model, train_x,</span><br><span class="line">	train_y, cv=<span class="number">5</span>, scoring=<span class="string">'accuracy'</span>).mean())</span><br><span class="line">model.fit(train_x, train_y)</span><br><span class="line">pred_test_y = model.predict(test_x)</span><br><span class="line">print((pred_test_y == test_y).sum() /</span><br><span class="line">	pred_test_y.size)</span><br><span class="line">data = [[<span class="string">'Tuesday'</span>, <span class="string">'12:30:00'</span>, <span class="string">'21'</span>, <span class="string">'23'</span>]]</span><br><span class="line">data = np.array(data).T</span><br><span class="line">x = []</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> range(len(data)):</span><br><span class="line">	encoder = encoders[row]</span><br><span class="line">	x.append(encoder.transform(data[row]))</span><br><span class="line">x = np.array(x).T</span><br><span class="line">pred_y = model.predict(x)</span><br><span class="line">print(encoders[<span class="number">-1</span>].inverse_transform(pred_y))</span><br></pre></td></tr></table></figure></p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/AI进阶/" rel="tag"># AI进阶</a>
          
            <a href="/tags/机器学习/" rel="tag"># 机器学习</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/20/ml/回归/" rel="next" title="机器学习-回归问题">
                <i class="fa fa-chevron-left"></i> 机器学习-回归问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/01/ml/聚类/" rel="prev" title="机器学习-聚类问题">
                机器学习-聚类问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#简单分类"><span class="nav-number">1.</span> <span class="nav-text">简单分类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#逻辑回归分类器"><span class="nav-number">2.</span> <span class="nav-text">逻辑回归分类器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#朴素贝叶斯分类"><span class="nav-number">3.</span> <span class="nav-text">朴素贝叶斯分类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-划分训练集和测试集"><span class="nav-number">3.1.</span> <span class="nav-text">1. 划分训练集和测试集</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-评价分类器的性能"><span class="nav-number">3.2.</span> <span class="nav-text">2. 评价分类器的性能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-交叉验证"><span class="nav-number">3.3.</span> <span class="nav-text">3. 交叉验证</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-混淆矩阵"><span class="nav-number">3.4.</span> <span class="nav-text">4. 混淆矩阵</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-分类报告"><span class="nav-number">3.5.</span> <span class="nav-text">5. 分类报告</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十一、决策树分类"><span class="nav-number">4.</span> <span class="nav-text">十一、决策树分类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-验证曲线"><span class="nav-number">4.1.</span> <span class="nav-text">1. 验证曲线</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-学习曲线"><span class="nav-number">4.2.</span> <span class="nav-text">2. 学习曲线</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十二、支持向量机"><span class="nav-number">5.</span> <span class="nav-text">十二、支持向量机</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-原理"><span class="nav-number">5.1.</span> <span class="nav-text">1. 原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-接口"><span class="nav-number">5.2.</span> <span class="nav-text">2. 接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-线性核函数"><span class="nav-number">5.3.</span> <span class="nav-text">3. 线性核函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-多项式核函数"><span class="nav-number">5.4.</span> <span class="nav-text">4. 多项式核函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-径向基核函数"><span class="nav-number">5.5.</span> <span class="nav-text">5. 径向基核函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-样本均衡"><span class="nav-number">5.6.</span> <span class="nav-text">6. 样本均衡</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-置信概率"><span class="nav-number">5.7.</span> <span class="nav-text">7. 置信概率</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-网格搜索"><span class="nav-number">5.8.</span> <span class="nav-text">8. 网格搜索</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });
  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') { next = next.nextSibling }
        if (next && next.nodeName.toLowerCase() === 'br') { next.parentNode.removeChild(next) }
      }
    });
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      document.getElementById(all[i].inputID + '-Frame').parentNode.className += ' has-jax';
    }
  });
</script>
<script src="//cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
